package com.rpoonolly.simplegame.core.aabb;

import javax.vecmath.Vector2d;

import com.rpoonolly.simplegame.core.Collision;

public final class AABBCollision extends Collision<AABBEntity> implements Comparable<AABBCollision> {
	private final double nearDistX, nearDistY;
	private final double collisionTime;
	private final AABBCollisionSide collisionDirection;
	
	public AABBCollision(AABBEntity staticEntity, AABBEntity dynamicEntity, Vector2d v) {
		super(staticEntity, dynamicEntity, v);
		
		if (v.x > 0) {
			nearDistX = staticEntity.getX() - (dynamicEntity.getX() + dynamicEntity.getWidth());
		} else {
			nearDistX = dynamicEntity.getX() - (staticEntity.getX() + staticEntity.getWidth());
		}
		
		if (v.y > 0) {
			nearDistY = staticEntity.getY() - (dynamicEntity.getY() + dynamicEntity.getHeight());
		} else {
			nearDistY = dynamicEntity.getY() - (staticEntity.getY() + staticEntity.getHeight());
		}
		
		if ((getNearDistY() / Math.abs(v.y) > getNearDistX() / Math.abs(v.x) && v.y != 0) || v.x == 0) {
			collisionTime = getNearDistY() / Math.abs(v.y);
			collisionDirection = (v.y > 0) ? AABBCollisionSide.UP : AABBCollisionSide.DOWN;
		} else {
			collisionTime = getNearDistX() / Math.abs(v.x);
			collisionDirection = (v.x > 0) ? AABBCollisionSide.RIGHT : AABBCollisionSide.LEFT;
		}
	}
	
	private double getNearDistX() {
		return nearDistX;
	}

	private double getNearDistY() {
		return nearDistY;
	}

	public double getCollisionTime() {
		return collisionTime;
	}

	public AABBCollisionSide getCollisionDirection() {
		return collisionDirection;
	}

	@Override
	public int compareTo(AABBCollision other) {
		return (int) (collisionTime - other.collisionTime);
	}
}
